//
//  XueWeiRzViewController.m
//  marrymarry
//
//  Created by caofeng on 16/9/25.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * xueLiCellID =@"XueLiChoseTableViewCell";
static NSString * WriteCellID = @"WriteSchoolNameTableViewCell";
static NSString * sendPicCellID = @"sendXueLiPicTableViewCell";

#import "XueWeiRzViewController.h"
#import "XueLiChoseTableViewCell.h"
#import "WriteSchoolNameTableViewCell.h"
#import "saveFootView.h"
#import "sendXueLiPicTableViewCell.h"
#import "XPRZViewController.h"
@interface XueWeiRzViewController ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate>
{
    NSString * _NBStr;
      BOOL _isOnChecking;
    BOOL _isPassed;
    BOOL _isfailed;
    UIImage * _studyImg;
    NSString * _study_imgUrl;
    NSString * _collegeStr;
    NSString * _skillStr;
    int _signNum;
    NSMutableArray * _myPicArry;
    NSDictionary * _studyDic;
    

}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) saveFootView * footView;
@property (strong,nonatomic) NSMutableArray * dataArry;
@property (strong, nonatomic) UIPickerView * pickNewView;
@property (nonatomic, strong) NSArray *stringsArray;
@property (strong,nonatomic) UIView * SetView;
@property (strong,nonatomic) UIView * grayView;

@property (nonatomic, strong) NSArray<ZLSelectPhotoModel *> *lastSelectMoldels;
@property (nonatomic, strong) NSArray *arrDataSources;
@property (nonatomic,strong) NSArray * MyPicStrArry;
@property (strong , nonatomic) NSArray * selectPicArry;
@end

@implementation XueWeiRzViewController
//-(NSString *)otherid_str
//{
//    if (!_otherid_str) {
////        XPRZViewController * pvc = (XPRZViewController*)self.parentViewController;
//
//    }else{
//        NSLog(@"_otherid_str ====  %@",_otherid_str);
//    }
//    
//    return _otherid_str;
//}


///选择存储img的数组
-(NSArray *)selectPicArry
{
    if (!_selectPicArry) {
        _selectPicArry = [NSArray new];
    }
    return _selectPicArry;
}


-(NSArray*)stringsArray
{
    if (!_stringsArray) {
        //        全新、九成新、八成新、七成新、六成信息
        self.stringsArray = @[@"初中",@"高中",@"大专",@"本科",@"硕士",@"博士",@"博士后"];
    }
    return _stringsArray;
}

-(NSMutableArray *)dataArry
{
    if (!_dataArry) {
        _dataArry = [[NSMutableArray alloc]initWithArray:@[@"1",@"2",@"3",@"4"]];
        
    }
    return _dataArry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _myPicArry =[NSMutableArray new];
    // Do any additional setup after loading the view.
    self.myTableView.hidden = NO;
    NSLog(@"%d",self.isother);
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSLog(@"%@",self.otherid_str);
    
    [self setupTableViewFootView];
   
    
}




-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.otherid_str != nil) {
        self.isother = YES;
        [self requestTheNetWith:nil andURL:WATCHSTUDY_URL andDic:@{@"id":self.otherid_str}];
    }else{
        [self requestTheNetWith:nil andURL:WATCHSTUDY_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
    }
}


-(void)setupTableViewFootView
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 50)];
    self.myTableView.tableFooterView = footView;
    self.footView = [[[NSBundle mainBundle] loadNibNamed:@"saveFootView" owner:self options:nil] lastObject];
    self.footView.frame = CGRectMake(0, 0,self.myTableView.frame.size.width,50);
    [footView addSubview: self.footView];
    
    self.footView.saveFootBtn.layer.cornerRadius = 5;
    [self.footView.saveFootBtn addTarget:self action:@selector(pushMyPhoto) forControlEvents:UIControlEventTouchUpInside];

    
}


-(void)pushMyPhoto
{
    if (_collegeStr == nil) {
        [SVProgressHUD showErrorWithStatus:@"请填写您的大学"];
        return;
    }else if (_skillStr == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请填写您的专业"];
        return;
    }else if (_NBStr == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请选择您的学历"];
        return;
    }else if (_studyImg == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请上传您的照片"];
        return;
    }
    [self requestTheNetWith:self.selectPicArry andURL:UPDATESTUDY_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID],@"school":_collegeStr,@"major":_skillStr,@"education":_NBStr}];
}


#pragma mark UITableViewDatasource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataArry.count>0) {
        return self.dataArry.count;
    }else
    {
        return  0;
    }
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        XueLiChoseTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:xueLiCellID];
        if (!cell) {
            cell = [[XueLiChoseTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:xueLiCellID];
            
        }
        if (_isOnChecking||self.isother||_isPassed) {
            cell.userInteractionEnabled = NO;
        }else{
            cell.userInteractionEnabled = YES;
        }
        if (_NBStr != nil) {
            cell.resultLabel.text = _NBStr;
        }else{
            cell.resultLabel.text = @"";
        }
        
        return cell;
    }else if (indexPath.section ==1 || indexPath.section ==3)
    {
        WriteSchoolNameTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WriteCellID];
        if (!cell) {
            cell = [[WriteSchoolNameTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:WriteCellID];
            
        }
        if (indexPath.section == 3) {
            cell.writeTextField.placeholder = @"填写专业";
        }
        if (indexPath.section == 1) {
            cell.writeTextField.tag = 2002;
        }else{
        cell.writeTextField.tag = 2001;
        }
        [cell.writeTextField addTarget:self action:@selector(textFieldChangeValue:) forControlEvents:UIControlEventEditingChanged];
        if (indexPath.section == 1) {
            if (_collegeStr !=nil) {
                cell.writeTextField.text = _collegeStr;
            }else
            {
                cell.writeTextField.text = @"";
            }
        }
        if (indexPath.section == 3) {
            if (_skillStr != nil) {
                cell.writeTextField.text = _skillStr;
            }else{
                cell.writeTextField.text = @"";
            }
        }
        
        if (_isOnChecking||self.isother||_isPassed) {
            cell.writeTextField.userInteractionEnabled = NO;
        }else{
            cell.writeTextField.userInteractionEnabled= YES;
        }
        return cell;

    }else if (indexPath.section ==2 )
    {
        sendXueLiPicTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:sendPicCellID];
        if (!cell) {
            cell = [[sendXueLiPicTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sendPicCellID];
            
        }
        
        if (_study_imgUrl != nil || _studyImg !=nil) {
            if (_isOnChecking || self.isother||_isPassed) {
                cell.delePhotoBtn.hidden= YES;
                cell.addPhotoImgView.userInteractionEnabled = NO;
            }else{
                cell.delePhotoBtn.hidden = NO;
            }
            cell.delePhotoBtn.tag = 3;
            [cell.delePhotoBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            if (_study_imgUrl != nil) {
                [cell.addPhotoImgView setImageWithURL:[NSURL URLWithString:_study_imgUrl]];
            }else{
                [cell.addPhotoImgView setImage:_studyImg];
            }
        }else{
            if (self.isother) {
                cell.addPhotoImgView.hidden = YES;
            }
            cell.delePhotoBtn.hidden = YES;
            cell.addPhotoImgView.userInteractionEnabled = YES;
            [cell.addPhotoImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
            myTap.usertype = @"3";
            [cell.addPhotoImgView addGestureRecognizer:myTap];
        }

        
        return  cell;
    }else
    {
        UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@""];
        return cell;
    }
   
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else
    {
        return 10;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        return 160;
    }else{
    return 60;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            self.grayView = [[UIView alloc]initWithFrame:ScreenRect];
            self.grayView.backgroundColor = [UIColor lightGrayColor];
            [self.view addSubview:self.grayView];
            self.SetView = [[UIView alloc]initWithFrame:CGRectMake(0,ScreenHeight - 360,WIDETH,60)];
            self.SetView.backgroundColor = [UIColor orangeColor];
            UIButton * cancelBtn = [[UIButton alloc]initWithFrame:CGRectMake(8,10,60, 40)];
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
            [cancelBtn addTarget:self action:@selector(cancelPicer) forControlEvents:UIControlEventTouchUpInside];
            UIButton * sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDETH-8-60,10,60, 40)];
            [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
            [sureBtn addTarget:self action:@selector(surePicer) forControlEvents:UIControlEventTouchUpInside];
            
            [self.SetView addSubview:cancelBtn];
            [self.SetView addSubview:sureBtn];
            [self.view addSubview:self.SetView];
            
            self.pickNewView = [[UIPickerView alloc]initWithFrame:CGRectMake(0,ScreenHeight-300,WIDETH,300)];
            self.pickNewView.backgroundColor = [UIColor whiteColor];
            self.pickNewView.tag = indexPath.row;
            [self.pickNewView selectRow:0 inComponent:0 animated:YES];
            self.pickNewView.delegate =self;
            self.pickNewView.dataSource = self;
            _NBStr = self.stringsArray[0];
            [self.view addSubview:self.pickNewView];
            self.myTableView.userInteractionEnabled = NO;
        }
    }
    
}

-(void)textFieldChangeValue:(UITextField*)textField
{
    /** 专业 **/
    if (textField.tag == 2001) {
        _skillStr = textField.text;
    }else if (textField.tag == 2002)
    {
        _collegeStr = textField.text;
    }
}


/** 取消picerview **/
-(void)cancelPicer
{
    self.myTableView.userInteractionEnabled = YES;
    [self.SetView removeFromSuperview];
    [self.pickNewView removeFromSuperview];
    [self.grayView removeFromSuperview];
}

/** pickerView确定 **/
-(void)surePicer
{
    [self cancelPicer];
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark --- 与DataSource有关的代理方法
//返回列数（必须实现）
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

//返回每列里边的行数（必须实现）
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    //如果是第一列
    if (component == 0) {
        //返回姓名数组的个数
        return self.stringsArray.count;
    }
    else
    {
        return 1;
        //返回表情数组的个数
        //        return self.iconArray.count;
    }
    
}

#pragma mark --- 与处理有关的代理方法
//设置组件的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 0) {
        return ScreenWidth;
    }
    else
    {
        return 80;
    }
    
}
//设置组件中每行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    if (component == 0) {
        return 60;
    }
    else
    {
        return 60;
    }
}
//设置组件中每行的标题row:行
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return self.stringsArray[row];
    }
    else
    {
        return self.stringsArray[row];
    }
}


//选中行的事件处理
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        NSLog(@"%@",self.stringsArray[row]);
        [pickerView selectedRowInComponent:0];
        //        //重新加载数据
        //                [pickerView reloadAllComponents];
        //        //重新加载指定列的数据
        //                [pickerView reloadComponent:0];
        
    }
    else
    {
        NSLog(@"%@",self.stringsArray[row]);
    }
    //    _isFirstin = YES;
    //    _signNum = (int)pickerView.tag;
    _NBStr = self.stringsArray[row];
    
    
}


-(void)deletImgBtn:(UIButton * )deleBtn
{
    
        _studyImg = nil;
    
    [self.myTableView reloadData];
}

///添加照片
-(void)addphotoWithTap:(CFUITapGestureRecognizer * )myTap
{
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大选择数
    actionSheet.maxSelectCount = 1;
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    actionSheet.isInVC = YES;
    weakify(self);
    [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:self.lastSelectMoldels completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
        strongify(weakSelf);
        strongSelf.arrDataSources = selectPhotos;
        strongSelf.lastSelectMoldels = selectPhotoModels;
        NSLog(@"%@", selectPhotos);
        self.selectPicArry = strongSelf.arrDataSources;
        
        _studyImg = self.selectPicArry[0];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:2];
        [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }];
    
}


-(void)setFootViewBtn
{
    if (_isOnChecking) {
        [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
    }else if(_isPassed)
    {
        [self.footView.saveFootBtn setTitle:@"审核通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }else if (_isfailed)
    {
        [self.footView.saveFootBtn setTitle:@"审核不通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = YES;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }
    
}

#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic;
{ [_myPicArry removeAllObjects];
    if (myRequestArry.count> 0) {
        
         _studyDic = @{@"imgname":@"educationimg",@"pic":myRequestArry[0]};
        [_myPicArry addObject:_studyDic];
        
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:_myPicArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if (code == 1) {
                if ([returnData[@"status"] intValue] == 0) {
                    [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
                    self.footView.saveFootBtn.userInteractionEnabled = NO;
                    self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
                    _isOnChecking = YES;
                    [self.myTableView reloadData];

                }else if ([returnData[@"status"] intValue] == 1)
                {
                    [self.footView.saveFootBtn setTitle:@"已通过审核" forState:UIControlStateNormal];
                    self.footView.saveFootBtn.userInteractionEnabled = NO;
                    self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
                    _isOnChecking = NO;
                    _isPassed = YES;
                    [self.myTableView reloadData];
                }else if ([returnData[@"status"] intValue] == 2)
                {
                    [self.footView.saveFootBtn setTitle:@"审核被拒绝" forState:UIControlStateNormal];
                    self.footView.saveFootBtn.userInteractionEnabled = NO;
                    self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
                    _isOnChecking = NO;
                    _isPassed = NO;
                    _isfailed = YES;
                    [self.myTableView reloadData];
                    
                }
                
                
            }
            
        } failure:^(NSError *error) {
            NSLog(@"失败");
            
        } showHUD:nil];
        [self.myTableView reloadData];
    
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            
            if (code == 1) {
                NSLog(@"%@",returnData);
//                _houseImg_Url = returnData[@"deedPhoto"];
                if ([returnData[@"status"] intValue] == 0) {
                    _isOnChecking = YES;
                    [self setFootViewBtn];
                    }else if ([returnData[@"status"] intValue] == 1)
                    {
                        _isOnChecking = NO;
                        _isPassed = YES;
                        [self setFootViewBtn];
                        
                    }else if ([returnData[@"status"] intValue] == 2)
                    {
                        _isfailed = YES;
                        [self setFootViewBtn];
                    }
                else{
                    _isOnChecking = NO;
                    }
                _collegeStr = returnData[@"school"];
                _skillStr = returnData[@"major"];
                _NBStr = returnData[@"education"];
                _study_imgUrl = returnData[@"graduationPhoto"];
                [self.myTableView reloadData];
                

                
            }else
            {
                if (self.isother) {
                    self.footView.hidden=YES;
                    [self.myTableView reloadData];
                }
            }

            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
    }


    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
